package edu.pku.sei.modeler.uml.commands.activity;

import java.util.List;

import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;

import edu.pku.sei.modeler.model.core.MetaModel;
import edu.pku.sei.modeler.model.core.MetaModelElement;
import edu.pku.sei.modeler.model.core.MetaNamedElement;
import edu.pku.sei.modeler.model.core.MetaPackage;
import edu.pku.sei.modeler.model.structure.MetaDiagram;
import edu.pku.sei.modeler.model.structure.MetaNode;
import edu.pku.sei.modeler.uml.commands.NestedElementCreateCommand;
import edu.pku.sei.modeler.uml.commands.NestedElementDeleteCommand;

public class DeleteNodeInPartitionCommand extends NestedElementDeleteCommand {

	public DeleteNodeInPartitionCommand(MetaNode node, MetaNode fatherNode, Boolean isDeletedFromDiagram) {
		super(node, fatherNode, isDeletedFromDiagram);
	}

	public boolean canExecute() {
		return node != null && fatherNode != null;
	}

	@Override
	protected void deleteModelElement() {
		MetaPackage pkg = findPackage(fatherNode.getModel(), fatherNode.getDiagram());
		MetaModelElement ele = node.getModelElement(); 
		if (pkg != null) {
			if (ele instanceof MetaPackage) {
				pkg.getSubPackages().remove(ele);
			} else if (ele instanceof MetaNamedElement)
				pkg.getNamedElements().remove(ele);
			else
				pkg.getOtherElements().remove(ele);
		}
	}
	
	protected MetaPackage findPackage(MetaModel model, MetaDiagram diagram) {
		if (model == null || diagram == null)
			return null;
		List pkgs = model.getPackages();
		for (int i = 0; i < pkgs.size(); i++) {
			MetaPackage pkg = (MetaPackage) pkgs.get(i);
			MetaPackage result = findPackage(pkg, diagram);
			if (result != null)
				return result;
		}
		return null;
	}

	protected MetaPackage findPackage(MetaPackage pkg, MetaDiagram diagram) {
		if (pkg == null)
			return null;
		List diags = pkg.getDiagrams();
		for (int i = 0; i < diags.size(); i++) {
			if (diags.get(i) == diagram)
				return pkg;
		}
		List pkgs = pkg.getSubPackages();
		for (int i = 0; i < pkgs.size(); i++) {
			MetaPackage subPkg = (MetaPackage) pkgs.get(i);
			MetaPackage result = findPackage(subPkg, diagram);
			if (result != null)
				return result;
		}
		return null;
	}
}
